package com.tkjt.pms.modules.gm.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tkjt.pms.common.entity.*;
import com.tkjt.pms.common.utils.*;
import com.tkjt.pms.modules.common.mapper.*;
import com.tkjt.pms.modules.gm.vo.CommentsDataVo;
import com.tkjt.pms.modules.gm.vo.CommentsVo;
import com.tkjt.pms.modules.gm.vo.TkGmScoresVo;
import com.tkjt.pms.modules.scoring.model.ScoreDatagridResponseModel;
import com.tkjt.pms.server.common.DepartAndInfoTool;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hmef.attribute.MAPIAttribute;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tkjt.pms.calc.KpiCalculator;
import com.tkjt.pms.common.vos.TkIndexValueForScoreVO;
import com.tkjt.pms.modules.common.service.IndexBaseService;
import com.tkjt.pms.modules.gm.mapper.TkGmMapper;
import com.tkjt.pms.modules.gm.service.TkGmBizService;
import com.tkjt.pms.modules.kpiadmin.mapper.DataGridMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Transactional
public abstract class TkGmBizServiceBase extends IndexBaseService implements TkGmBizService {
	
	@Autowired
	protected TkIndexValueMapper tkIndexValueMapper;
	@Autowired
	protected TkIndexValueCommentsMapper tkIndexValueCommentsMapper;
	@Autowired
	protected TkGmMapper tkGmMapper;
	@Autowired
	protected SysDepartMapper departMapper;
	@Autowired
	DataGridMapper dataGridMapper;
	@Autowired
	protected TkIndexValueAuditMapper tkIndexValueAuditMapper;
	@Autowired
	protected KpiCalculator kpiCalculator;
	@Autowired
	protected PMSCommonMapper commonMapper;
	@Autowired
	protected TkIndexValueMirrorMapper tkIndexValueMirrorMapper;
	@Autowired
	protected SysUserMapper userMapper;
	@Autowired
	private DepartAndInfoTool departAndInfoTool;
	@Autowired
	private TkDepartGroupMapper tkDepartGroupMapper;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private TkIndexValueReferenceMapper tkIndexValueReferenceMapper;
	@Autowired
	private TkChangeReportMapper tkChangeReportMapper;

	@Override
	public Map<String, Object> gmGradedRadio(LoginUser loginUser,String yearMonth,String dataType) {
		
		log.info("user={},indexYearMonth={},dataType={}");
		
		QueryWrapper<TkIndexValue> objectQueryWrapper = new QueryWrapper<>();
		String[] roleCodes = {"ykgm"};
		List<String> userNames = sysUserMapper.selectUserNameByRoleCodes(roleCodes);
		objectQueryWrapper.eq("INDEX_EXECUTOR", userNames.get(0));
		TkDepartGroup tkDepartGroup = new TkDepartGroup();
		//虚拟机构
		tkDepartGroup.setDepartAttr("ATRV0000");
		List<String> orgCodes = departAndInfoTool.getOrgCodesByOrgGroup(tkDepartGroup);
		objectQueryWrapper.notIn("INDEX_DEPART", orgCodes);
		if(StringUtils.isEmpty(yearMonth)) {
			yearMonth = EsDateUtils.getIndexYearMonth(new Date());
		}
		objectQueryWrapper.eq("year", yearMonth.substring(0,4));
		objectQueryWrapper.eq("data_type", dataType);
		
		Integer needCount = tkIndexValueMapper.selectCount(objectQueryWrapper);
		String montnStr = yearMonth.substring(4);
		if (montnStr.contains("0")) {
			montnStr = montnStr.substring(1);
		}
		int month = Integer.valueOf(montnStr);
		objectQueryWrapper.ge("INDEX_VALUE_STATUS", month);
		Integer editedCount = tkIndexValueMapper.selectCount(objectQueryWrapper);
		Map<String, Object> map = new HashMap<>();
		map.put("needCount", needCount);
		//editedCount是待评分  变量名有歧义
		map.put("editedCount", needCount-editedCount);
		map.put("indexYearMonth", yearMonth);
		return map;
	}

	@Override
	public Result<?> gmDatagrid(TkIndexValueForScoreVO tkIndexValue, Integer pageNo, Integer pageSize, LoginUser loginUser,String dataType) {
		Map<String, Object> queryTotalGrade = new HashMap<>();
		int count = 0;
		queryTotalGrade.put("min", (pageNo - 1) * pageSize);
		queryTotalGrade.put("max", pageSize);
		String month = "";
		String yearmonth = tkIndexValue.getIndexYearMonth();
		if (null == yearmonth || "".equals(yearmonth)) {
			return Result.ok(null);
		}
		queryTotalGrade.put("year", yearmonth.substring(0, 4));
		month = yearmonth.substring(4);
		queryTotalGrade.put("month", month);
		queryTotalGrade.put("dataType", dataType);
		queryTotalGrade.put("indexDepart", tkIndexValue.getIndexDepart());
		if(StringUtils.isNotEmpty(tkIndexValue.getIndexGroup())){
			queryTotalGrade.put("indexGroup", "A01A01A01".equalsIgnoreCase(tkIndexValue.getIndexGroup()) ? "C" : "G");
		}
		List<TkIndexValueForScoreVO> totalGradeList = new ArrayList<>();
		List<String> orgSorts = new ArrayList<>();
		String currentYearMonth = EsDateUtils.getIndexYearMonth(new Date());
		queryTotalGrade.put("column",tkIndexValue.getColumn());
		queryTotalGrade.put("order",tkIndexValue.getOrder());
		//sortType==grade  排序根据镜像（往期考核期）或者当前考核表总计得分降序排列   否则按照部门code升序排序
		//排序根据镜像（往期考核期）或者当前考核表总计得分降序排列
		if(currentYearMonth.equals(yearmonth)){
			totalGradeList = tkGmMapper.selectTotalGradeList(queryTotalGrade);
			count = tkGmMapper.selectTotalGradeCount(queryTotalGrade);
			orgSorts = tkGmMapper.selectOrgSortByTotalGrade(queryTotalGrade);
		}else{
			queryTotalGrade.put("mirrorCode", "MC"+yearmonth);
			totalGradeList = tkGmMapper.selectMirrorTotalGradeList(queryTotalGrade);
			count = tkGmMapper.selectMirrorTotalGradeCount(queryTotalGrade);
			orgSorts = tkGmMapper.selectOrgSortByMirrorTotalGrade(queryTotalGrade);
		}
		Map<String,Integer> sortMap = new HashMap<>();
		for(int i= 0 ; i < orgSorts.size() ; i++){
			sortMap.put(orgSorts.get(i),i+1);
		}
		Map<String, Object> queryIndexValue = new HashMap<>();
		String[] roleCodes = {"ykgm"};
		List<String> userNames = sysUserMapper.selectUserNameByRoleCodes(roleCodes);
		queryIndexValue.put("indexExecutor",userNames.get(0));
        queryIndexValue.put("indexExecutorDepart",loginUser.getOrgCode());
		queryIndexValue.put("year", yearmonth.substring(0, 4));
		for (int i = 0; i < totalGradeList.size(); i++) {
			totalGradeList.get(i).setTotalGrade(DepartCode.formateForDouble(totalGradeList.get(i).getMTotal()));
			String indexScorer = totalGradeList.get(i).getIndexScorer();
			String indexDepart = totalGradeList.get(i).getIndexDepart();
			queryIndexValue.put("indexScorer", indexScorer);
			queryIndexValue.put("indexDepart", indexDepart);
			QueryWrapper<TkDepartGroup> departGroupQueryWrapper = new QueryWrapper<>();
			departGroupQueryWrapper.lambda().eq(TkDepartGroup::getIndexDepart,indexDepart);

			TkDepartGroup tkDepartGroup = tkDepartGroupMapper.selectOne(departGroupQueryWrapper);
			List<String> infoAttrs = new ArrayList<>();
			infoAttrs.add(InfoAttrUtil.SHUANG_XIANG_PING_FEN);
			List<String> indexValueCodes = departAndInfoTool.getIndexValueCodesByOrgGroup(tkDepartGroup.getIndexGroupCode(),infoAttrs);
			queryIndexValue.put("indexValueCodes", indexValueCodes);
			queryIndexValue.put("dataType", dataType);
			TkIndexValueForScoreVO indexValue = tkGmMapper.selectOneIndexValaue(queryIndexValue);
			totalGradeList.get(i).setId(indexValue.getId());
			totalGradeList.get(i).setSortNum(sortMap.get(indexDepart+"@"+indexScorer));
			totalGradeList.get(i).setIndexValueCode(indexValue.getIndexValueCode());
			totalGradeList.get(i).setIndexValueName(indexValue.getIndexValueName());
			totalGradeList.get(i).setIndexYearMonth(yearmonth);
			totalGradeList.get(i).setIndexScorer(indexValue.getIndexScorer());
			totalGradeList.get(i).setIndexScorerName(indexValue.getIndexScorerName());
			totalGradeList.get(i).setIndexDepartName(indexValue.getIndexDepartName());
			QueryWrapper<TkIndexValueReference> referenceQueryWrapper = new QueryWrapper<>();
			referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexDepart,indexDepart);
			referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexScorer,indexScorer);
			referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexValueCode,indexValue.getIndexValueCode());
			referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexYearMonth,yearmonth);
			referenceQueryWrapper.lambda().eq(TkIndexValueReference::getWhich,"supervise");
			List<TkIndexValueReference> tkIndexValueReferences = tkIndexValueReferenceMapper.selectList(referenceQueryWrapper);
			totalGradeList.get(i).setSuperviseGrade(tkIndexValueReferences.size() == 0  ? null : DepartCode.formateForDouble(tkIndexValueReferences.get(0).getValue()));
			totalGradeList.get(i).setGrade(DepartCode.formateForDouble(TkGradeUtil.createGrade(indexValue, month)));
			/*totalGradeList.get(i).setM01(indexValue.getM01() == 0 ? null : DepartCode.formateForDouble(indexValue.getM01()));
			totalGradeList.get(i).setM02(indexValue.getM02() == 0 ? null : DepartCode.formateForDouble(indexValue.getM02()));
			totalGradeList.get(i).setM03(indexValue.getM03() == 0 ? null : DepartCode.formateForDouble(indexValue.getM03()));
			totalGradeList.get(i).setM04(indexValue.getM04() == 0 ? null : DepartCode.formateForDouble(indexValue.getM04()));
			totalGradeList.get(i).setM05(indexValue.getM05() == 0 ? null : DepartCode.formateForDouble(indexValue.getM05()));
			totalGradeList.get(i).setM06(indexValue.getM06() == 0 ? null : DepartCode.formateForDouble(indexValue.getM06()));
			totalGradeList.get(i).setM07(indexValue.getM07() == 0 ? null : DepartCode.formateForDouble(indexValue.getM07()));
			totalGradeList.get(i).setM08(indexValue.getM08() == 0 ? null : DepartCode.formateForDouble(indexValue.getM08()));
			totalGradeList.get(i).setM09(indexValue.getM09() == 0 ? null : DepartCode.formateForDouble(indexValue.getM09()));
			totalGradeList.get(i).setM10(indexValue.getM10() == 0 ? null : DepartCode.formateForDouble(indexValue.getM10()));
			totalGradeList.get(i).setM11(indexValue.getM11() == 0 ? null : DepartCode.formateForDouble(indexValue.getM11()));
			totalGradeList.get(i).setM12(indexValue.getM12() == 0 ? null : DepartCode.formateForDouble(indexValue.getM12()));*/
			// 查询该指标该部门双向评分所有评分部门对其的评分之和
			Map<String, Object> param = new HashMap<>();
			param.put("indexDepart", indexDepart);
			param.put("indexValueCode", indexValue.getIndexValueCode());
			param.put("indexScorer", totalGradeList.get(i).getIndexScorer());
			param.put("dataType", dataType);
			TkIndexValue sumIndexValue = tkIndexValueMapper.selectSumByParam(param);
			param.put("month", "m"+month);
			Map<String,Double> minAndMaxGrage = tkIndexValueMapper.selectMaxAndMinGrageByParam(param);
			if(sumIndexValue==null || minAndMaxGrage == null) {
				totalGradeList.get(i).setAvegGrade(0.00D);
				totalGradeList.get(i).setMaxGrade(0.00D);
				totalGradeList.get(i).setMinGrade(0.00D);
			} else {
				double gradeTotal = TkGradeUtil.createGrade(sumIndexValue, month);
				totalGradeList.get(i).setAvegGrade(DepartCode.formateForDouble(DoubleUtil.div(gradeTotal, sumIndexValue.getMTotal())));
				totalGradeList.get(i).setMaxGrade(DepartCode.formateForDouble(minAndMaxGrage.get("maxGrade")));
				totalGradeList.get(i).setMinGrade(DepartCode.formateForDouble(minAndMaxGrage.get("minGrade")));
			}
			QueryWrapper<TkIndexValueComments> queryWrapperSdf = new QueryWrapper<>();
			queryWrapperSdf.lambda().eq(TkIndexValueComments::getIndexValueId, totalGradeList.get(i).getId()).eq(TkIndexValueComments::getIndexValueM, month);
			/*TkIndexValueComments commentsEntity = tkIndexValueCommentsMapper.selectOne(queryWrapperSdf);
			if (commentsEntity != null) {
				totalGradeList.get(i).setIndexValueComments(commentsEntity.getIndexValueComments());
			}*/
			List<TkIndexValueComments> tkIndexValueCommentsEntitys = tkIndexValueCommentsMapper.selectList(queryWrapperSdf);
			List<ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean> scoreComments=new ArrayList<>();
			if (tkIndexValueCommentsEntitys != null && tkIndexValueCommentsEntitys.size() > 0) {
				for (TkIndexValueComments t : tkIndexValueCommentsEntitys) {
					ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean scoreCommentBean=new ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean();
					scoreCommentBean.setTitle(t.getIndexValueCommentTitle());
					scoreCommentBean.setContent(t.getIndexValueComments());
					scoreCommentBean.setCode(t.getIndexValueCommentCode());
					scoreComments.add(scoreCommentBean);
				}
			}
			totalGradeList.get(i).setScoreComments(scoreComments);

		}
		Page<TkIndexValueForScoreVO> finalPage = new Page<TkIndexValueForScoreVO>(pageNo, pageSize);
		finalPage.setTotal(count);
		finalPage.setCurrent(pageNo);
		finalPage.setSize(pageSize);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.setPages(pages);
		finalPage.setRecords(totalGradeList);
		return Result.ok(finalPage);
	}

	@Override
	public Map<String, Object> cgDatagrid(LoginUser loginUser,TkIndexValueForScoreVO tkIndexValue, Integer pageNo, Integer pageSize,String dataType) {
		Map<String, Object> queryIndexValue = new HashMap<>();
		int count = 0;

		List<TkIndexValueForScoreVO> list = new ArrayList<>();
		if(pageNo == 1){
			Map<String, Object> queryGmValue = new HashMap<>();
			queryGmValue.put("indexDepart", tkIndexValue.getIndexDepart());
			queryGmValue.put("indexScorer", tkIndexValue.getIndexScorer());
			queryGmValue.put("indexValueCode", tkIndexValue.getIndexValueCode());
			queryGmValue.put("indexExecutorDepart", loginUser.getOrgCode());
			queryGmValue.put("indexAttr", InfoAttrUtil.SHUANG_XIANG_PING_FEN);
			queryGmValue.put("dataType", dataType);
			list = tkGmMapper.gmDatagrid(queryGmValue);
		}

		if(pageNo == 1){
			queryIndexValue.put("min", (pageNo - 1) * pageSize);
			queryIndexValue.put("max", pageSize-1);
		}else{
			queryIndexValue.put("min", (pageNo - 1) * pageSize-1);
			queryIndexValue.put("max", pageSize);
		}
		queryIndexValue.put("indexDepart", tkIndexValue.getIndexDepart());
		queryIndexValue.put("indexScorer", tkIndexValue.getIndexScorer());
		queryIndexValue.put("indexValueCode", tkIndexValue.getIndexValueCode());
		queryIndexValue.put("indexExecutorDepart", tkIndexValue.getIndexExecutorDepart());
		Calendar cal = Calendar.getInstance();

		String yearMonth = tkIndexValue.getYear();
		String month = EsDateUtils.getIndexYearMonth(new Date()).substring(4);

		queryIndexValue.put("indexAttr", InfoAttrUtil.SHUANG_XIANG_PING_FEN);
		queryIndexValue.put("dataType", dataType);
		List<TkIndexValueForScoreVO> doubleList = new ArrayList<>();
		doubleList = tkGmMapper.gmDatagrid(queryIndexValue);
		count = tkGmMapper.gmDatagridCount(queryIndexValue);
		count+=1;
		list.addAll(doubleList);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setM01(list.get(i).getM01() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM01()));
			list.get(i).setM02(list.get(i).getM02() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM02()));
			list.get(i).setM03(list.get(i).getM03() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM03()));
			list.get(i).setM04(list.get(i).getM04() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM04()));
			list.get(i).setM05(list.get(i).getM05() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM05()));
			list.get(i).setM06(list.get(i).getM06() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM06()));
			list.get(i).setM07(list.get(i).getM07() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM07()));
			list.get(i).setM08(list.get(i).getM08() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM08()));
			list.get(i).setM09(list.get(i).getM09() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM09()));
			list.get(i).setM10(list.get(i).getM10() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM10()));
			list.get(i).setM11(list.get(i).getM11() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM11()));
			list.get(i).setM12(list.get(i).getM12() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM12()));
			// 查询该指标该部门双向评分所有评分部门对其的评分之和
			/*Map<String, Object> param = new HashMap<>();
			param.put("indexDepart", list.get(i).getIndexDepart());
			param.put("indexScorer", list.get(i).getIndexScorer());
			param.put("indexValueCode", list.get(i).getIndexValueCode());
			param.put("indexExecutorDepart", list.get(i).getIndexExecutorDepart());
			param.put("indexExecutor", list.get(i).getIndexExecutor());
			param.put("month", month);
			param.put("dataType", dataType);
			Double average = tkIndexValueMapper.selectAverageByParam(param);
			list.get(i).setAvegGrade(DepartCode.formateForDouble(average));*/
			//查评分意见
			QueryWrapper<TkIndexValueComments> queryWrapperSdf = new QueryWrapper<>();
			queryWrapperSdf.lambda().eq(TkIndexValueComments::getIndexValueId, list.get(i).getId()).eq(TkIndexValueComments::getIndexValueM,month);
			List<TkIndexValueComments> tkIndexValueCommentsEntitys = tkIndexValueCommentsMapper.selectList(queryWrapperSdf);
			List<ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean> scoreComments=new ArrayList<>();
			if (tkIndexValueCommentsEntitys != null && tkIndexValueCommentsEntitys.size() > 0) {
				for (TkIndexValueComments t : tkIndexValueCommentsEntitys) {
					ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean scoreCommentBean=new ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean();
					scoreCommentBean.setTitle(t.getIndexValueCommentTitle());
					scoreCommentBean.setContent(t.getIndexValueComments());
					scoreCommentBean.setCode(t.getIndexValueCommentCode());
					scoreComments.add(scoreCommentBean);
				}
			}
			list.get(i).setScoreComments(scoreComments);
		}
		Map<String,Object> finalPage = new HashMap<String,Object>();
		finalPage.put("total",count);
		finalPage.put("size",pageSize);
		finalPage.put("current",pageNo);
		finalPage.put("orders",new ArrayList<String>());
		finalPage.put("searchCount",true);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.put("pages",pages);
		finalPage.put("records",list);
		return finalPage;
	}

	@Override
	public Map<String, Object> doubleDatagrid(TkIndexValueForScoreVO tkIndexValue, Integer pageNo, Integer pageSize,String dataType) {
		Map<String, Object> queryIndexValue = new HashMap<>();
		int count = 0;

		queryIndexValue.put("min", (pageNo - 1) * pageSize);
		queryIndexValue.put("max", pageSize);
		queryIndexValue.put("indexDepart", tkIndexValue.getIndexDepart());
		queryIndexValue.put("indexScorer", tkIndexValue.getIndexScorer());
		queryIndexValue.put("indexValueCode", tkIndexValue.getIndexValueCode());
		queryIndexValue.put("indexExecutorDepart", tkIndexValue.getIndexExecutorDepart());
		Calendar cal = Calendar.getInstance();

		String yearMonth = tkIndexValue.getYear();
		String month = EsDateUtils.getIndexYearMonth(new Date()).substring(4);

		queryIndexValue.put("indexAttr", InfoAttrUtil.SHUANG_XIANG_PING_FEN);
		queryIndexValue.put("dataType", dataType);
		List<TkIndexValueForScoreVO> list = new ArrayList<>();
		list = tkGmMapper.gmDatagrid(queryIndexValue);
		count = tkGmMapper.gmDatagridCount(queryIndexValue);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setM01(list.get(i).getM01() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM01()));
			list.get(i).setM02(list.get(i).getM02() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM02()));
			list.get(i).setM03(list.get(i).getM03() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM03()));
			list.get(i).setM04(list.get(i).getM04() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM04()));
			list.get(i).setM05(list.get(i).getM05() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM05()));
			list.get(i).setM06(list.get(i).getM06() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM06()));
			list.get(i).setM07(list.get(i).getM07() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM07()));
			list.get(i).setM08(list.get(i).getM08() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM08()));
			list.get(i).setM09(list.get(i).getM09() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM09()));
			list.get(i).setM10(list.get(i).getM10() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM10()));
			list.get(i).setM11(list.get(i).getM11() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM11()));
			list.get(i).setM12(list.get(i).getM12() == 0 ? 0.0 : DepartCode.formateForDouble(list.get(i).getM12()));
			// 查询该指标该部门双向评分所有评分部门对其的评分之和
			/*Map<String, Object> param = new HashMap<>();
			param.put("indexDepart", list.get(i).getIndexDepart());
			param.put("indexScorer", list.get(i).getIndexScorer());
			param.put("indexValueCode", list.get(i).getIndexValueCode());
			param.put("indexExecutorDepart", list.get(i).getIndexExecutorDepart());
			param.put("indexExecutor", list.get(i).getIndexExecutor());
			param.put("month", month);
			param.put("dataType", dataType);
			Double average = tkIndexValueMapper.selectAverageByParam(param);
			list.get(i).setAvegGrade(DepartCode.formateForDouble(average));*/
			//查评分意见
			QueryWrapper<TkIndexValueComments> queryWrapperSdf = new QueryWrapper<>();
			queryWrapperSdf.lambda().eq(TkIndexValueComments::getIndexValueId, list.get(i).getId()).eq(TkIndexValueComments::getIndexValueM,month);
			List<TkIndexValueComments> tkIndexValueCommentsEntitys = tkIndexValueCommentsMapper.selectList(queryWrapperSdf);
			List<ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean> scoreComments=new ArrayList<>();
			if (tkIndexValueCommentsEntitys != null && tkIndexValueCommentsEntitys.size() > 0) {
				for (TkIndexValueComments t : tkIndexValueCommentsEntitys) {
					ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean scoreCommentBean=new ScoreDatagridResponseModel.RecordsBean.ScoreCommentBean();
					scoreCommentBean.setTitle(t.getIndexValueCommentTitle());
					scoreCommentBean.setContent(t.getIndexValueComments());
					scoreCommentBean.setCode(t.getIndexValueCommentCode());
					scoreComments.add(scoreCommentBean);
				}
			}
			list.get(i).setScoreComments(scoreComments);
		}
		Map<String,Object> finalPage = new HashMap<String,Object>();
		finalPage.put("total",count);
		finalPage.put("size",pageSize);
		finalPage.put("current",pageNo);
		finalPage.put("orders",new ArrayList<String>());
		finalPage.put("searchCount",true);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.put("pages",pages);
		finalPage.put("records",list);
		return finalPage;
	}


	@Override
	public Result<?> scoreDatagrid(TkIndexValueForScoreVO tkIndexValue, Integer pageNo, Integer pageSize,String dataType) {
		Map<String, Object> queryIndexValue = new HashMap<>();
		int count = 0;
		queryIndexValue.put("min", (pageNo - 1) * pageSize);
		queryIndexValue.put("max", pageSize);
		queryIndexValue.put("indexDepart", tkIndexValue.getIndexDepart());
		queryIndexValue.put("indexExecutorDepart", tkIndexValue.getIndexExecutorDepart());
		if(tkIndexValue.getIndexGroup() != null && !"".equals(tkIndexValue.getIndexGroup())){
			String orgGroup = OrgGroupUtil.changeToCG(tkIndexValue.getIndexGroup());
			queryIndexValue.put("indexGroup", orgGroup);
		}

		String yearMonth = tkIndexValue.getIndexYearMonth();
		if (null == yearMonth || "".equals(yearMonth)) {
			return Result.ok(null);
		}
		queryIndexValue.put("mirrorCode", "MC"+yearMonth);
		List<String> infoAttrs = new ArrayList<>();
		infoAttrs.add(InfoAttrUtil.ZONG_JI);
		List<String> indexValueCodes = departAndInfoTool.getIndexValueCodesByOrgGroup(null,infoAttrs);
		queryIndexValue.put("indexValueCodes", indexValueCodes);
		queryIndexValue.put("dataType", dataType);
		queryIndexValue.put("monthSign",yearMonth);

		List<TkIndexValueForScoreVO> list = tkGmMapper.gmHistoryDatagrid(queryIndexValue);
		count = tkGmMapper.gmDHistoryatagridCount(queryIndexValue);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setIndexYearMonth(yearMonth);
			list.get(i).setTotalGrade(list.get(i).getMTotal() == 0 ? null : DepartCode.formateForDouble(list.get(i).getMTotal()));
			list.get(i).setM01(list.get(i).getM01() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM01()));
			list.get(i).setM02(list.get(i).getM02() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM02()));
			list.get(i).setM03(list.get(i).getM03() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM03()));
			list.get(i).setM04(list.get(i).getM04() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM04()));
			list.get(i).setM05(list.get(i).getM05() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM05()));
			list.get(i).setM06(list.get(i).getM06() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM06()));
			list.get(i).setM07(list.get(i).getM07() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM07()));
			list.get(i).setM08(list.get(i).getM08() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM08()));
			list.get(i).setM09(list.get(i).getM09() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM09()));
			list.get(i).setM10(list.get(i).getM10() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM10()));
			list.get(i).setM11(list.get(i).getM11() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM11()));
			list.get(i).setM12(list.get(i).getM12() == 0 ? null : DepartCode.formateForDouble(list.get(i).getM12()));
		}
		Page<TkIndexValueForScoreVO> finalPage = new Page<TkIndexValueForScoreVO>(pageNo, pageSize);
		finalPage.setTotal(count);
		finalPage.setCurrent(pageNo);
		finalPage.setSize(pageSize);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.setPages(pages);
		finalPage.setRecords(list);
		return Result.ok(finalPage);
	}

	@Override
	public Result<?> scoreGmDatagrid(TkIndexValueForScoreVO tkIndexValue,String dataType) {
		String yearMonth = tkIndexValue.getIndexYearMonth();
		if(yearMonth == null || "".equals(yearMonth)){
			return Result.error("参数缺失");
		}
		String indexDepart = tkIndexValue.getIndexDepart();
		if(indexDepart == null || "".equals(indexDepart)){
			return Result.error("参数缺失");
		}
		String indexScorer = tkIndexValue.getIndexScorer();
		if(indexScorer == null || "".equals(indexScorer)){
			return Result.error("参数缺失");
		}
		String year = yearMonth.substring(0,4);
		String month = yearMonth.substring(4);
		List<String> infoAttrs = new ArrayList<>();
		infoAttrs.add(InfoAttrUtil.ZONG_JI);
		List<String> indexCodes = departAndInfoTool.getIndexCodesByOrgGroup(null,infoAttrs);
		Map<String, Object> mTotalMirrorMap = new HashMap<String, Object>();
		String mirrorCode = "MC"+yearMonth;
		String currentYearMonth = EsDateUtils.getIndexYearMonth(new Date());
		Map<String,Object> indexValueMap = new HashMap<>();
		Map<String,Object> param = new HashMap<>();
		param.put("year",year);
		param.put("indexDepart",indexDepart);
		param.put("indexScorer",indexScorer);
		param.put("indexCodes",indexCodes);
		param.put("dataType", dataType);
		if(yearMonth.equals(currentYearMonth)){
			indexValueMap = tkIndexValueMapper.getIndexValueMapByParam(param);
		}else{
			param.put("mirrorCode",mirrorCode);
			indexValueMap = tkIndexValueMapper.getMirrorIndexValueMapByParam(param);
		}
		for (int index = 1; index <= 12; index++) {
			// String mirrorCode = "MC"+""+"11";
			String monthStr = index < 10 ? "0"+index : String.valueOf(index);
			int monthInt = Integer.valueOf(month.startsWith("0") ? month.substring(1) : month);
			if (index <= monthInt) {
				mTotalMirrorMap.put("m" +monthStr, indexValueMap != null ? DepartCode.formateForDouble(Double.valueOf(indexValueMap.get("m" +monthStr).toString())) : null);
			} else {
				mTotalMirrorMap.put("m" + monthStr, null);
			}
		}

		mTotalMirrorMap.put("mTotal",indexValueMap != null ? DepartCode.formateForDouble(Double.valueOf(indexValueMap.get("mTotal").toString())) : null);
		mTotalMirrorMap.put("title",year+"年绩效得分记录");
		mTotalMirrorMap.put("indexDepart",indexDepart);

		QueryWrapper<SysDepart> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.lambda().eq(SysDepart::getOrgCode,tkIndexValue.getIndexDepart());
		SysDepart sysDepart = departMapper.selectOne(objectQueryWrapper);
		mTotalMirrorMap.put("indexDepartName",sysDepart != null ? sysDepart.getDepartName() : null);
		mTotalMirrorMap.put("indexScorer",indexScorer);
		SysUser user = userMapper.getUserByName(indexScorer);
		mTotalMirrorMap.put("indexScorerName",user != null ? user.getRealname() : null);
		return Result.ok(mTotalMirrorMap);
	}

	@Override
	public Result<?> saveScores(String currentUser, String indexYearMonth, List<TkIndexValueForScoreVO> tkIndexValueVOs,String dataType) {
		if (StringUtils.isEmpty(currentUser)) {
			return Result.error("登录账号不存在！");
		}
		if (CollectionUtils.isEmpty(tkIndexValueVOs)) {
			return Result.error("保存数据不能为空！");
		}
		String year = indexYearMonth.substring(0, 4);
		String month = indexYearMonth.substring(4);
		String indexValueStatus = month;
		if(month.startsWith("0")){
			indexValueStatus = month.substring(1);
		}
		// 检查部门批标是否在审核中
		{
			String currentYearMonth = EsDateUtils.getIndexYearMonth(new Date());
			if(currentYearMonth.equals(indexYearMonth)){
				String indexGroup = tkIndexValueVOs.get(0).getIndexDepart().substring(0, 9);
				QueryWrapper<TkIndexValueAudit> queryWrapperSdf = new QueryWrapper<>();
				queryWrapperSdf.lambda().eq(TkIndexValueAudit::getIndexGroup, "C".equals(indexGroup) ? "A01A01A01" : "A01A01A02");
				queryWrapperSdf.lambda().eq(TkIndexValueAudit::getIndexValueY, year);
				queryWrapperSdf.lambda().eq(TkIndexValueAudit::getIndexValueM, month);
				queryWrapperSdf.lambda().eq(TkIndexValueAudit::getDataType,dataType);
				TkIndexValueAudit indexValueAuditEntity = tkIndexValueAuditMapper.selectOne(queryWrapperSdf);
				if (indexValueAuditEntity != null) {
					if("2".equals(indexValueAuditEntity.getAuditStatus())){
						return Result.error("部门指标正在审核中，不允许修改");
					}else if("3".equals(indexValueAuditEntity.getAuditStatus())){
						return Result.error("部门指标已审核，不允许修改");
					}

				}
			}else{
				return Result.error("镜像数据，不允许修改");
			}
		}
		// 总经理保存要进行绩效计算
		{
			// VO转 entity
			List<TkIndexValue> tkIndexValues = new ArrayList<TkIndexValue>();
			for (TkIndexValueForScoreVO vo : tkIndexValueVOs) {
				Map<String,Object> param = new HashMap<>();
				param.put("id",vo.getId());
				//总经理和绩效管理员修改时同时修改kpi和budget
				List<TkIndexValue> oldTkIndexValues = tkGmMapper.selectAllDataTypeIndexValueByParam(param);
				for (TkIndexValue oldTkIndexValue : oldTkIndexValues){
					TkIndexValue tkIndexValue = new TkIndexValue();
					tkIndexValue.setId(oldTkIndexValue.getId());
					tkIndexValue.setGrade(vo.getGrade());
					tkIndexValue.setIndexValueStatus(indexValueStatus);
					tkIndexValue.setScoreComments(vo.getScoreComments());
					tkIndexValues.add(tkIndexValue);
				}

				//督办得分保存修改
				if(vo.getSuperviseGrade() != null){
					TkIndexValue oldIndexValue = oldTkIndexValues.get(0);
					QueryWrapper<TkIndexValueReference> referenceQueryWrapper = new QueryWrapper<>();
					referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexDepart,oldIndexValue.getIndexDepart());
					referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexScorer,oldIndexValue.getIndexScorer());
					referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexValueCode,oldIndexValue.getIndexValueCode());
					referenceQueryWrapper.lambda().eq(TkIndexValueReference::getIndexYearMonth,indexYearMonth);
					referenceQueryWrapper.lambda().eq(TkIndexValueReference::getWhich,"supervise");
					List<TkIndexValueReference> tkIndexValueReferences = tkIndexValueReferenceMapper.selectList(referenceQueryWrapper);
					if(tkIndexValueReferences.size() == 0){
						TkIndexValueReference tkIndexValueReference = new TkIndexValueReference();
						tkIndexValueReference.setIndexDepart(oldIndexValue.getIndexDepart());
						tkIndexValueReference.setIndexScorer(oldIndexValue.getIndexScorer());
						tkIndexValueReference.setIndexValueCode(oldIndexValue.getIndexValueCode());
						tkIndexValueReference.setIndexYearMonth(indexYearMonth);
						tkIndexValueReference.setDataType("");
						tkIndexValueReference.setWhich("supervise");
						tkIndexValueReference.setValue(vo.getSuperviseGrade());
						tkIndexValueReference.setCreateDate(new Date());
						tkIndexValueReference.setCreateBy(currentUser);
						tkIndexValueReferenceMapper.insert(tkIndexValueReference);
					}else{
						TkIndexValueReference tkIndexValueReference = tkIndexValueReferences.get(0);
						tkIndexValueReference.setValue(vo.getSuperviseGrade());
						tkIndexValueReference.setUpdateDate(new Date());
						tkIndexValueReference.setUpdateBy(currentUser);
						tkIndexValueReferenceMapper.updateById(tkIndexValueReference);
					}
				}
			}
			for (TkIndexValue saveValue : tkIndexValues) {
				saveFinalRows(saveValue, currentUser,indexYearMonth);
			}
		}
		return Result.ok();
	}

	@Override
	public void caculateGrade(String currentUser,List<TkIndexValueForScoreVO> tkIndexValues,String dataType){
		Map<String, Object> map = new HashMap<>();
		map.put("username", currentUser);
		List<String> roleCodes = commonMapper.getRoleCodeByParam(map);
		if(roleCodes.contains("ykgm") || roleCodes.contains("ykkpiowner")) {
			List<String> unitOrgCodes = new ArrayList<>();
			List<String> groupOrgCodes = new ArrayList<>();
			for (TkIndexValueForScoreVO item : tkIndexValues) {
				if ("A01A01A01".equals(item.getIndexDepart().substring(0, 9))) {
					unitOrgCodes.add(item.getIndexDepart());
				} else {
					groupOrgCodes.add(item.getIndexDepart());
				}
			}
			List<String> indexCodes = new ArrayList<>();
			if (unitOrgCodes.size() > 0) {
				indexCodes = IndexCodesRepositories.findIndexGroupRepository(CalcuConsts.INDEX_UNIT);
				for (String indexCode : indexCodes) {
					log.debug("indexCode={}",indexCode);
					//todo
					//kpiCalculator.doCalculatorForDepartCodes("C", indexCode, unitOrgCodes, null);
				}
			}
			if (groupOrgCodes.size() > 0) {
				indexCodes = IndexCodesRepositories.findIndexGroupRepository(CalcuConsts.INDEX_GROUP);
				for (String indexCode : indexCodes) {
					log.debug("indexCode={}",indexCode);
					//todo
					//kpiCalculator.doCalculatorForDepartCodes("G", indexCode, groupOrgCodes, null);
				}
			}
		}
	}

	@Override
	public Result<?> getCommentsReport(LoginUser loginUser, CommentsVo commentsVo, String dataType) {
        Map<String,Object> map = new HashMap<>();
	    String id = commentsVo.getId();
        if(StringUtils.isEmpty(id)){
            map.put("indexOrgCode",commentsVo.getIndexOrgCode());
            map.put("scorerCode",commentsVo.getScorerCode());
            map.put("orgGroup",commentsVo.getIndexOrgCode().startsWith("A01A01A01") ? "C":"G");
        }else{
            map.put("id",id);
        }
        map.put("dataType",dataType);
        Map<String,Object> indexValueMap= tkGmMapper.selectIndexValueByParam(map);
        if(indexValueMap == null){
            return Result.error("双向评分不存在！");
        }
        String indexDepart = indexValueMap.get("indexDeparName").toString();
        String indexScorer = indexValueMap.get("indexScorerName").toString();
        String indexExecutorDepart = indexValueMap.get("indexExecutorDepartName").toString();
        String indexExecutor = indexValueMap.get("indexExecutorName").toString();
        CommentsVo comment = new CommentsVo();
        comment.setIndexDepart(indexDepart);
        comment.setIndexScorer(indexScorer);
        comment.setIndexExecutorDepart(indexExecutorDepart);
        comment.setIndexExecutor(indexExecutor);
        List<CommentsDataVo> data = new ArrayList<>();
        for(int i = 1 ; i <= 12 ; i++){
            CommentsDataVo commentsDataVo = new CommentsDataVo();
            QueryWrapper<TkIndexValueComments> commentsWrapper = new QueryWrapper<>();
            commentsWrapper.lambda().eq(TkIndexValueComments::getIndexValueId,indexValueMap.get("id").toString());
            commentsWrapper.lambda().eq(TkIndexValueComments::getIndexValueM,i<10 ? "0"+i : i );
            commentsWrapper.lambda().orderByAsc(TkIndexValueComments::getIndexValueCommentSeq);
            List<TkIndexValueComments> tkIndexValueCommentsList = tkIndexValueCommentsMapper.selectList(commentsWrapper);
            commentsDataVo.setMonth(i+"月");
            if(tkIndexValueCommentsList.size() > 0){
                List<String> comments = new ArrayList<>();
                for(TkIndexValueComments tkIndexValueComments : tkIndexValueCommentsList){
                    comments.add(tkIndexValueComments.getIndexValueCommentTitle()+"："+tkIndexValueComments.getIndexValueComments());
                }
                commentsDataVo.setComments(comments);
            }
            String monthStr = "";
            if(i < 10){
				monthStr = "m0"+i;
			}else{
				monthStr = "m"+i;
			}
			commentsDataVo.setGrade(DoubleUtil.formateForDoubleScale0((Double)indexValueMap.get(monthStr)).toString());
			QueryWrapper<TkChangeReport> changeWrapper = new QueryWrapper<>();
			changeWrapper.lambda().eq(TkChangeReport::getIndexDepart,commentsVo.getIndexOrgCode());
			changeWrapper.lambda().eq(TkChangeReport::getIndexScorer,commentsVo.getScorerCode());
			changeWrapper.lambda().eq(TkChangeReport::getDataType,dataType);
			changeWrapper.lambda().eq(TkChangeReport::getIndexYearMonth,commentsVo.getYear()+ (i<10 ? "0"+i : i));
			TkChangeReport tkChangeReport = tkChangeReportMapper.selectOne(changeWrapper);
			commentsDataVo.setChangeReport(tkChangeReport == null ? "" : tkChangeReport.getComments());
			data.add(commentsDataVo);
        }
		comment.setData(data);
		return Result.ok(comment);
	}


}
